﻿using System;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using DslModeling=global::Microsoft.VisualStudio.Modeling;
using DslValidation=global::Microsoft.VisualStudio.Modeling.Validation;

namespace Salamanca.Sdml
{

    [DslValidation.ValidationState(DslValidation.ValidationState.Enabled)]
    partial class EnumValue
    {

        [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification="Domain property custom storage")]
        public string GetNameAndUnderlyingValueValue()
        {
            return this.Name.Trim()+" = "+this.UnderlyingValue.Trim();
        }

        public void SetNameAndUnderlyingValueValue(string newValue)
        {
            string[] separated=newValue.Split(new char[] { '=' });
            if (separated.Length>0)
                this.Name=separated[0].Trim();
            if (separated.Length>1)
                this.UnderlyingValue=separated[1].Trim();
        }

        /// <summary>Ensures that enumeration values are valid.</summary>
        [DslValidation.ValidationMethod(DslValidation.ValidationCategories.Menu|DslValidation.ValidationCategories.Open|DslValidation.ValidationCategories.Save)]
        private void ValidateUnderlyingValue(DslValidation.ValidationContext context)
        {
            // Empty values are invalid
            if (string.IsNullOrEmpty(UnderlyingValue))
            {
                context.LogError(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.SR.UnderlyingValueCannotBeEmpty,
                        DomainEnum.Name,
                        Name
                    ),
                    "SDML12",
                    this
                );
                return;
            }

            // Values must be convertible to the underlying type
            if (Array.IndexOf(EnumTypesProviderConverter.IntegralTypes, DomainEnum.UnderlyingType)>=0)
            {
                try
                {
                    ((IConvertible)UnderlyingValue).ToType(TypesProvider.GetType(DomainEnum).DataType, CultureInfo.InvariantCulture);
                } catch (Exception ex)
                {
                    context.LogError(
                        string.Format(
                            CultureInfo.CurrentCulture,
                            Resources.SR.UnderlyingValueCannotBeConvertedToUnderlyingType,
                            UnderlyingValue,
                            DomainEnum.UnderlyingType,
                            ex.Message
                        ),
                        "SDML13",
                        this
                    );
                }
            }
        }
    }
}
